﻿/****************************** Module Header ******************************\
 * Module Name:  TimerHelper.cs
 * Module Version:  1.0.0 (2014-4-8)
 * Copyright (c) AnyEB.Com (14507247@qq.com)
 * 
 * This class is use for run a mutex program. 
 * 
 * This source is subject to the GPL License.
 * See http://www.gnu.org/licenses/gpl.html.
 * All other rights reserved.
 * 
 * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
 * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace UCF.Core.Forms
{
    /// <summary>
    /// 定时器帮助类
    /// </summary>
    /// <remarks>2014-4-8 by sutroon</remarks>
    public class TimerHelper
    {
        Dictionary<string, Timer> dictTimer = new Dictionary<string, Timer>();

        public void CountDown(string name, Action actAfter, Action actReback, Action<int> actEff = null, int second = 6, int inteval = 1000)
        {
            if (actAfter != null) actAfter();
            Timer tm;
            if (dictTimer.ContainsKey(name))
            {
                tm = dictTimer[name];
            }
            else
            {
                tm = new Timer() { Interval = inteval };
                tm.Tick += (object sender, EventArgs e) =>
                {
                    int i = (int)tm.Tag;
                    tm.Tag = i - 1;
                    if (actEff != null) actEff(i);
                    if (i == 0)
                    {
                        if (actReback != null) actReback();
                        tm.Enabled = false;
                    }
                };
                dictTimer.Add(name, tm);
            }
            tm.Tag = second;
            tm.Enabled = true;
            tm.Start();
        }
    }
}
